import {setClipboardData} from "@/common/costum.js"
import store from '@/store/index.js'
import {ybDownload} from "@/common/sdk/yb.js"
import {config} from "@/common/config.js"
//下载文件
export function downloadFile(url) {
	url = config.cos.baseUrl +url
	let isfinsh = true
	uni.showLoading({title:"文件下载中..."})
	function type(url){
		let temp = url.split(".")
		let type = temp[temp.length - 1]
		if(["doc","docx","xls","xlsx","pdf","pdfx","ppt","pptx"].includes(type)){
			return "document"
		}else if(["png","jpg","jpeg","gif"].includes(type)){
			return "image"
		}else if(["mp4","avi","mov","flv"].includes(type)){
			return "video"
		}else{
			return "other"
		}
	}
	// #ifdef MP
	uni.downloadFile({
		url: url, //仅为示例，并非真实的资源
		success: (res) => {
			if (res.statusCode === 200) {
				let that = this;
				let file =  res.tempFilePath
				switch(type(url)){
					case "document":
						uni.openDocument({filePath: file,fail(){isfinsh=false}});break;
					case "image":
						uni.saveImageToPhotosAlbum({filePath: file,fail(){isfinsh=false} });break;
					case "video":
						uni.saveVideoToPhotosAlbum({filePath: file,fail(){isfinsh=false}} );break;
					case "other": //设置下载链接到剪贴板，这里需要使用官方的下载通道下载否则会因为防盗链接导致下载失败
						setClipboardData(url).then(res=>{
							isfinsh=null;
							uni.showToast({title:"此文件微信暂时不支持下载，已经复制下载链接，移步到浏览器下载",icon:"none"})
						})
				}
				if(isfinsh===true){
					uni.showToast({title:"下载成功"})
				}else if(isfinsh===false){
					uni.showToast({title:"下载失败",icon:"none"})
				}
				uni.hideLoading()
			}
		}
	});
	// #endif

	// #ifdef H5
	console.log(store.getters.Device)
	if(store.getters.Device=="yiban"){
		ybDownload(url)
	}
	if(store.getters.Device=="h5"){
		let dload = document.createElement("a");
		dload.download = ''; // 设置下载的文件名，默认是'下载'
		dload.href = url;
		document.body.appendChild(dload);
		dload.click();
		dload.remove(); // 下载之后把创建的元素删除
	}
	uni.hideLoading()
	// #endif
}

export function strlen(str){
	var len = 0;
	for (var i=0; i<str.length; i++) {   
	 var c = str.charCodeAt(i);   
	 if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))  
	    len++;   
	 else  len+=3;   
	}   
	return len;  
}

export function substr(str,maxlen){
	var len = 0;
	for (var i=0; i<str.length; i++) {   
		 var c = str.charCodeAt(i);   
		 if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))  
			len++;   
		 else  len+=3;
		 if(len>maxlen){
			 return str.substr(0,i)
		 }
	}   
	return str;  
}
// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields()
	}
}

// 添加日期范围
export function addDateRange(params, dateRange) {
	var search = params
	search.beginTime = ''
	search.endTime = ''
	if (dateRange != null && dateRange !== '') {
		search.beginTime = this.dateRange[0]
		search.endTime = this.dateRange[1]
	}
	return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = []
	Object.keys(datas).map((key) => {
		if (datas[key].dictValue === ('' + value)) {
			actions.push(datas[key].dictLabel)
			return false
		}
	})
	return actions.join('')
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments;
	var flag = true;
	var i = 1
	str = str.replace(/%s/g, function() {
		var arg = args[i++]
		if (typeof arg === 'undefined') {
			flag = false
			return ''
		}
		return arg
	})
	return flag ? str : ''
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str === 'undefined' || str === 'null') {
		return ''
	}
	return str
}


export function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return (false);
}

export function getParam(variable, url) {
	var query = url.split("?")[1]
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return (false);
}

export function toChinesNum(num) {
	let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	let unit = ["", "十", "百", "千", "万"];
	num = parseInt(num);
	let getWan = (temp) => {
		let strArr = temp.toString().split("").reverse();
		let newNum = "";
		for (var i = 0; i < strArr.length; i++) {
			newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] +
				(strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
		}
		return newNum;
	}
	let overWan = Math.floor(num / 10000);
	let noWan = num % 10000;
	if (noWan.toString().length < 4) {
		noWan = "0" + noWan;
	}
	return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}

export function formatZero(num, len) {
	if (String(num).length > len) return num;
	return (Array(len).join(0) + num).slice(-len);
}

export function condCurTime(time) {
	var t = getTargetTime(time)
	var c = new Date().getTime()
	if (t > c) return true
	else return false
}

function getTargetTime(t){
    var d = t.split(" ")[0],
        h = t.split(" ")[1],
        date = new Date()

    date.setYear(d.split("-")[0])
    date.setMonth(d.split("-")[1] - 1)
    date.setDate(d.split("-")[2])

    date.setHours(h.split(":")[0])
    date.setMinutes(h.split(":")[1])
    date.setSeconds(h.split(":")[2])
    
    return date.getTime()    
}

export function condTime(start,end) {
	var s = getTargetTime(start)
	var e = getTargetTime(end)
	if (e > s) return true
	else return false
}

export function curDate() {
	var date = new Date()
	return date.getFullYear() + "-" + formatZero((date.getMonth() + 1), 2) + "-" + formatZero(date.getDate(), 2)
}

export function sortrandom(){
	return 0.5 - Math.random()
}

export function formatSeconds(value,fh="时",fm="分",fs="秒") {
    let result = parseInt(value)
    let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
 
    let res = '';
    if(h !== '00') res += `${h}${fh}`;
    if(m !== '00') res += `${m}${fm}`;
    res += `${s}${fs}`;
    return res;
  }